package com.lmt.ymcc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lmt.ymcc.domain.Login;
import com.lmt.ymcc.dto.LoginDto;
import com.lmt.ymcc.mapper.LoginMapper;
import com.lmt.ymcc.result.JSONResult;
import com.lmt.ymcc.service.ILoginService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lmt.ymcc.utils.AssertUtil;
import com.lmt.ymcc.utils.HttpUtil;
import org.springframework.stereotype.Service;

import java.time.Year;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author AmazingXu
 * @since 2022-08-05
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    private static final String TOKEN_URL = "http://localhost:10030/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&code=59cCzg&redirect_uri=http://www.baidu.com&password=%s";

    // 同意认证
    @Override
    public JSONResult common(LoginDto dto) {
        Integer type = dto.getType();
        String clientId = null;
        String secret = null;
        if (type == 0) {
            clientId = "admin";
            secret = "123";
            // 管理端登录
        }else if (type == 1) {
            // 客户端登录
            clientId = "website";
            secret = "123";
        }
        AssertUtil.isNotNull(clientId, "非法请求");
        String tokenURL = String.format(TOKEN_URL, clientId, secret,dto.getUsername(), dto.getPassword());
        String result = HttpUtil.sendPost(tokenURL, null);
        Map map = JSONObject.parseObject(result, Map.class);
        if (result.contains("error_description")) {
            return JSONResult.error("用户名或者密码错误");
        }else {
            String expires_in = map.get("expires_in").toString();
            long timeOut = System.currentTimeMillis() - Long.valueOf(expires_in);
            map.put("expiresTime", timeOut);
            return JSONResult.success(map);
        }
    }
}
